import "https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.min.js";
import "https://cdn.bootcdn.net/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js";
import {
    Indexhead
} from "./index_module.js";


class Cartlist {
    constructor() {
        this.indexHead = new Indexhead();
        this.render();
        this.chooseGoods();
    }


    //渲染
    render() {
        if ($.cookie('productId') && $.cookie('productNum')) {
            this.sidArr = $.cookie('productId').split(',');
            this.numArr = $.cookie('productNum').split(',');
            let that = this;
            $.ajax({
                url: 'http://10.31.163.57/gree/php/alldata.php',
                dataType: 'json',
            }).done(function(dataArr) {
                $.each(dataArr, function(dataindex, datavalue) { //遍历所有数据中的对象
                    $.each(that.sidArr, function(sidindex, sidvalue) { //遍历cookie中的sid数组
                        if (datavalue.sid === sidvalue) { //通过cookie中的sid找到对应sid的对象数据，再依次渲染出来。
                            let str = '';
                            str += `     <li class="pad_t20">
                                                <input type="checkbox" checked="">
                                            </li>
                                            <li class="man1_pro">
                                                <a href="list.html?id=${sidvalue}">
                                                    <img style="line-height:1.5;word-break:break-all " title="${datavalue.title}" class="wid_80 hei_80 border-4" src="${datavalue.url}">
                                                </a>
                                            </li>
                                            <li class="man1_n" style="vertical-align: middle;">
                                                <p class="man1_name">
                                                       <a href="list.html?id=${sidvalue}" title="${datavalue.title}" target="_blank">${datavalue.title}</a>
                                                </p>
                                                 <div style="width: 180px;">
                                                     <a href="list.html?id=" title="匹数:正1.5匹&nbsp; &nbsp; " target="_blank">匹数:正1.5匹&nbsp; &nbsp; </a>
                                                </div>
                                             </li>
                                             <li class="price_font">￥${datavalue.price}</li>
                                             <li class="number">
                                                 <div class="wrap-input">
                                                     <div class="btn-reduce" href="#">-</div>
                                                     <input value="${that.numArr[sidindex]}" class="productNumD">
                                                     <div class="btn-add" href="#">+</div>
                                                 </div>
                                                <div class="stock_box">
                                                     库存:有货
                                                 </div>
                                             </li>
                                             <li class="price_total"><strong>￥${(datavalue.price*that.numArr[sidindex]).toFixed(2)}</strong></li>
                                             <li class="delete">
                                                 <span>【删除】<span>
                                             </li>`;
                            that.renderul = document.createElement('ul'); //创建ul
                            $(that.renderul).addClass('listbox').html(str); //给ul加上listbox类名并渲染
                            $(that.renderul).attr('sid', sidvalue); //给每个列表加上自定义的sid类
                            $('.content-list').append(that.renderul);
                        }
                    })
                })
                that.total();
            })
        } else { //cookie没有存储时将全选框设置为为勾选
            $('.select-all').prop('checked', false);
        }
    }

    total() { //统计所有选中的商品的总数量和价格
        this.totalPrice = 0;
        this.totalNum = 0;
        let that = this;
        $('.listbox').each(function(index, ele) {
            if ($(this).find('.pad_t20 input').is(':checked')) { //判断复选框是否被选中
                that.totalPrice += parseFloat($('.price_total strong').eq(index).html().substring(1)); //将价格累加
                that.totalNum += parseInt($('.productNumD').eq(index).val()); //将数量累加
            }
        })
        $('.total_num').html(this.totalNum); //总数量赋值
        $('.set_right .price_font').html('￥' + this.totalPrice.toFixed(2)); //总价赋值
    }

    chooseGoods() {
        let that = this;

        //全选和单独选则
        $('.select-all').on('click', function() { //点击全选框，将所有的复选框都修改成点击的全选框的状态
            $('.content-list').find('.pad_t20 input').prop('checked', $(this).prop('checked'));
            $('.select-all').prop('checked', $(this).prop('checked'));
            if (!$.cookie('productId') || !$.cookie('productNum')) {
                $('.select-all').prop('checked', false);
            }
            that.total();
        })
        $('.content-list').on('click', '.pad_t20 input', function() { //将已选中的复选框的长度与商品的复选框的总长度对比
            that.checkedLength = $('.content-list').find('.pad_t20 input:checked').length; //已选中的复选框的长度
            that.inputLength = $('.content-list').find('.pad_t20 input').length; //商品的复选框的总长度对比
            if (that.checkedLength === that.inputLength) { //相等就表示已经全选中了
                $('.select-all').prop('checked', true);
            } else {
                $('.select-all').prop('checked', false);
            }
            that.total();
        })

        //数量的变化
        //添加
        $('.content-list').on('click', '.btn-add', function() {
            that.num = $(this).parents('.listbox').find('.productNumD').val(); //保存当前商品数量
            that.num++;
            $(this).parents('.listbox').find('.productNumD').val(that.num);
            that.univalence = parseFloat($(this).parents('.listbox').find('.price_font').html().substring(1)) //保存单价
            $(this).parents('.listbox').find('.price_total strong').html('￥' + (that.num * that.univalence).toFixed(2));
            that.total();
            that.saveCookie($(this));
        })

        //减少
        $('.content-list').on('click', '.btn-reduce', function() {
            that.num = $(this).parents('.listbox').find('.productNumD').val(); //保存当前商品数量
            that.num--;
            if (that.num < 1) { //商品数量至少为1
                that.num = 1;
            }
            $(this).parents('.listbox').find('.productNumD').val(that.num);
            that.univalence = parseFloat($(this).parents('.listbox').find('.price_font').html().substring(1)) //保存单价
            $(this).parents('.listbox').find('.price_total strong').html('￥' + (that.num * that.univalence).toFixed(2));
            that.total();
            that.saveCookie($(this));
        })

        //自定义数量
        $('.content-list').on('input', '.productNumD', function() {
            if (!/^\d+$/.test($(this).val())) { //输入的不是数字时将商品数量变为1
                $(this).val(1);
            }
            that.univalence = parseFloat($(this).parents('.listbox').find('.price_font').html().substring(1)) //保存单价
            $(this).parents('.listbox').find('.price_total strong').html('￥' + ($(this).val() * that.univalence).toFixed(2));
            that.total();
            that.saveCookie($(this));
        })


        //单项删除
        $('.content-list').on('click', '.delete span', function() {
            if (confirm('确认删除？')) {
                that.removeCookie(that.sidArr, $(this).parents('.listbox').attr('sid'))
                $(this).parents('.listbox').remove();
                that.total();
            }
            if (!$.cookie('productId') || !$.cookie('productNum')) { //如果id和数量均没有数据，将全选框取消
                $('.select-all').prop('checked', false);
            }
        })

        //删除选中的
        $('.delete-checked').on('click', function() {
            if (confirm('确认删除？')) {
                $('.pad_t20 input:checked').each(function(index, ele) {
                    that.removeCookie(that.sidArr, $(ele).parents('.listbox').attr('sid'))
                    $(ele).parents('.listbox').remove();
                })
            }
            that.total();
            if (!$.cookie('productId') || !$.cookie('productNum')) { //如果id和数量均没有数据，将全选框取消
                $('.select-all').prop('checked', false);
            }
        })

    }

    saveCookie(obj) { //将修改后的数量传入cookie。参数为当前操作的元素对象
        this.index = this.sidArr.indexOf(obj.parents('.listbox').attr('sid'));
        this.numArr[this.index] = obj.parents('.listbox').find('.productNumD').val();
        $.cookie('productNum', this.numArr, { expires: 30, path: '/' });
    }

    removeCookie(arr, sid) { //删除传入的sid,及sid对应的数量
        let that = this
        $.each(arr, function(index, value) {
            if (value == sid) {
                that.sidArr.splice(index, 1);
                that.numArr.splice(index, 1);
            }
        })
        $.cookie('productId', this.sidArr, { expires: 30, path: '/' });
        $.cookie('productNum', this.numArr, { expires: 30, path: '/' });
    }
}

export {
    Cartlist
}